package cn.tsa.share.jdbc.shardingjdbc.db;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author hongwei
 */
public class DbRangeShardingAlgorithm implements RangeShardingAlgorithm<Long> {
    /**
     * Sharding.
     *
     * @param availableTargetNames available data sources or tables's names
     * @param shardingValue        sharding value
     * @return sharding results for data sources or tables's names
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
        Set<String> result = new LinkedHashSet<>();
        long lower = shardingValue.getValueRange().lowerEndpoint();
        long upper = shardingValue.getValueRange().upperEndpoint();
        int tableSize = availableTargetNames.size();
        long lowerIndex = lower % tableSize;
        long upperIndex = upper % tableSize;
        TreeSet<Long> treeSet = new TreeSet();
        treeSet.add(lowerIndex);
        treeSet.add(upperIndex);
        for (long i = treeSet.first(); i <= treeSet.last(); i++) {
            for (String each : availableTargetNames) {
                if (each.endsWith(i % tableSize + "")) {
                    result.add(each);
                }
            }
        }
        return result;
    }
}
